package com.suning.sawp.service.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 〈MD5Util工具类〉<br>
 * 〈功能详细描述〉
 * 
 * @author
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */

public class MD5Util {
    final static Logger LOGGER = LoggerFactory.getLogger(MD5Util.class);
    
    private MD5Util() {
    }
    
    public static String getMD5(String input, String inputCharset) {
        String s = "";
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            md.update(input.getBytes(inputCharset));
            byte tmp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            s = new String(str);
        } catch (Exception e) {

            LOGGER.error("Error Message is ", e);
        }
        return s;
    }

    /**
     * 
     * 功能描述:参数MD5加签 <br>
     * 〈功能详细描述〉
     * 
     * @param paramMap 需要加签的参数
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static String getSignStr(Map<String, Object> paramMap, String charset, String key) {
        if (paramMap.isEmpty()) {
            return null;
        }
        List<String> paramList = new ArrayList<String>(paramMap.size());
        if (paramMap.containsKey("sign") || paramMap.containsKey("sign_type") || paramMap.containsKey("signType")) {
            paramMap.remove("sign");
            paramMap.remove("sign_type");
            paramMap.remove("signType");
        }
        for (@SuppressWarnings("rawtypes")
        Entry entry : paramMap.entrySet()) {
            String s = entry.getKey() + "=" + (entry.getValue()==null?"":entry.getValue());
            paramList.add(s);
        }
        String[] signingParams = paramList.toArray(new String[] {});
        Arrays.sort(signingParams);
        String signingStr = StringUtils.join(signingParams, "&");
        return getMD5(signingStr + key, charset);
    }

}
